import 'package:json_annotation/json_annotation.dart';

part 'browsing_life_history_api.g.dart';
// {"userId":"ay17438172186697ZKXr","topicId":"1916147536738394113","coverImg":null,"title":"每一次都成功","userAvatar":"","nickName":"匿名用户","topicUserId":"ay1744470566617dT6G4","createTime":"2025-06-10 10:35:11"}

@JsonSerializable()
class ResponseBrowsingLifeHistoryApi {
  final int total;
  final List<TopicHistory> rows;

  ResponseBrowsingLifeHistoryApi({required this.total, required this.rows});

  factory ResponseBrowsingLifeHistoryApi.fromJson(Map<String, dynamic> json) =>
      _$ResponseBrowsingLifeHistoryApiFromJson(json);

  Map<String, dynamic> toJson() => _$ResponseBrowsingLifeHistoryApiToJson(this);
}

@JsonSerializable()
class TopicHistory {
  final String id;
  final String? mainImg;
  final String? title;
  final String? userAvatar;
  final String? nickName;
  final String? topicUserId;
  final String? createTime;

  factory TopicHistory.fromJson(Map<String, dynamic> json) {
    return TopicHistory(
      id: json['topicId'] ?? '',
      title: json['title'] ?? '',
      mainImg: _getImageUrl(json) ?? '',
      userAvatar: json['userAvatar'] ?? '',
      nickName: json['nickName'],
      topicUserId: json['topicUserId'],
      createTime: json['createTime'],
    );
  }

  TopicHistory({
    required this.id,
    required this.mainImg,
    required this.title,
    required this.userAvatar,
    required this.nickName,
    required this.topicUserId,
    required this.createTime,
  });

  static String? _getImageUrl(Map<dynamic, dynamic> json) {
    final Map<String, dynamic> safeJson = Map<String, dynamic>.from(json);
    if (safeJson['coverImg'] != null && safeJson['coverImg'] is String) {
      String mainImg = safeJson['coverImg'];
      if (mainImg.isNotEmpty) return mainImg;
    }
    return null;
  }
}
